package util.io;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * Created by Administrator on 2017/10/27.
 */
public class UploadDownloadFileUtil {

    private static final Logger log = LoggerFactory.getLogger(UploadDownloadFileUtil.class);


    /**
     * 文件保存到ftp
     *
     * @param multipartFile
     * @param middlePath
     * @return
     */
    public static String saveFile(MultipartFile multipartFile, String middlePath) {
        if (multipartFile == null || multipartFile.getSize() <= 0) {
            return null;
        }
        String uuid = UUID.randomUUID().toString();
        String extend = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        String path = middlePath + File.separator + uuid + extend;
        try {
            boolean b = FtpUtil.saveFileByRelativePath(multipartFile.getInputStream(), middlePath, uuid + extend);
            if (b == false) {
                return "-1";
            }
        } catch (Exception e) {
            log.warn("【Manual】=>读取失败{}", e.getMessage());
            return "-1";//文件读取出错
        }
        return path;
    }


    /**
     * 通过相对路径下载文件  本地文件不存在或为空时从ftp上下载
     *
     * @param relativePathName
     * @param newFileName
     * @param request
     * @return
     */

    public static ResponseEntity<byte[]> downFileByRelativePathName(String localFilePath, String relativePathName, String newFileName, HttpServletRequest request) {

        String absolutePathName = localFilePath + File.separator + relativePathName;

        if (absolutePathName == null || absolutePathName.equals("") || newFileName == null || newFileName.equals("")) {
            return null;
        }
        log.info("localFilePath={}", absolutePathName);

        //目录不存在时创建目录
        String parentPath = absolutePathName.substring(0, absolutePathName.lastIndexOf("\\"));
        File parentDir = new File(parentPath);
        if (!parentDir.exists()) {
             parentDir.mkdirs();
        }

        File file = new File(absolutePathName);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", encodeChineseDownloadFileName(newFileName, request));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            byte[] var2  = null;
            if(file.exists()){
              var2  = FileUtils.readFileToByteArray(file);
            }

            if (var2 == null || var2.length <= 0) {
                OutputStream os = new FileOutputStream(file);
                FtpUtil.getFileFromRelativePath(os, relativePathName);
                os.close();
                var2 = FileUtils.readFileToByteArray(file);
            }

            return new ResponseEntity<byte[]>(var2, headers, HttpStatus.OK);

        } catch (Exception e) {
            log.warn("【Manual】=>文件读取失败{}", e.getMessage());
        }
        return null;
    }

    /**
     * 文件名编码
     *
     * @param request
     * @param fileName
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String encodeChineseDownloadFileName(String fileName, HttpServletRequest request) {
        String resultFileName = fileName;
        String agent = request.getHeader("User-Agent").toUpperCase();
        if (null != agent) {
            try {
                if (agent.indexOf("FIREFOX") != -1 || agent.indexOf("CHROME") != -1) {  //firefox, chrome
                    resultFileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
                } else {  //ie7+
                    resultFileName = URLEncoder.encode(fileName, "UTF-8");
                    resultFileName = StringUtils.replace(resultFileName, "+", "%20");  //替换空格
                }
            } catch (Exception e) {}
        }
        return resultFileName;
    }


    /**
     * 删除文件
     * @param respurcePath   flag为false时

     * @param flag    true绝对定位 ， false使用相对路径（相对于basePaht，）
     * @return
     */
//    public  static boolean dropFile(String respurcePath,boolean flag){
//        String Path;
//        if (respurcePath==null){
//            return  false;
//        }
//        if (flag==true){
//            Path  = respurcePath;
//        }else {
//            Path  = basePath+respurcePath;
//        }
//        File file = new File(Path);
//        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
//        if (file.exists() && file.isFile()) {
//            if (file.delete()) {
//                log.info("删除单个文件" + Path + "成功！");
//                return true;
//            } else {
//                log.info("删除单个文件" + Path + "失败！");
//                return false;
//            }
//        } else {
//            log.info("删除单个文件失败：" + Path + "不存在！");
//            return false;
//        }
//    }


//    public static boolean saveFile(InputStream is, String path, String newName) {
//        if (is == null || path == null || path.equals("")) {
//            log.warn("输入流和路径都不能为空");
//            return false;
//        }
//        FileOutputStream out = null;
//        try {
//            path = path + newName;
//            out = new FileOutputStream(path);
//            byte[] tempbytes = new byte[1024];
//            int byteread = 0;
//            while ((byteread = is.read(tempbytes)) != -1) {
//                out.write(tempbytes);
//            }
//        } catch (Exception e) {
//            log.warn("【Manual】=>附件读取失败{}", e.getMessage());
//            return false;
//        } finally {
//            try {
//                out.close();
//            } catch (Exception e) {
//                log.warn("【Manual】=>{}", e.getMessage());
//            }
//            try {
//                is.close();
//            } catch (Exception e) {
//                log.warn("【Manual】=>{}", e.getMessage());
//            }
//        }
//        return true;
//    }


}
